import { PrismaClient } from "@prisma/client";
import Mock from "mockjs";
const Random = Mock.Random;

// 创建PrismaClient实例，并配置日志
const prisma = new PrismaClient({
  log: ["query"],
});

// 使用中间件打印查询时间
prisma.$use(async (params, next) => {
  const before = Date.now();
  const result = await next(params);
  const after = Date.now();
  console.log(
    `Query ${params.model}.${params.action} took ${after - before}ms`
  );
  return result;
});

async function create() {
  // --> create
  // const createResult = await prisma.wifi.create({
  //   data: {
  //     store_id: Mock.mock({
  //       "number|1-10": 1,
  //     }).number,
  //     ssid: Random.word(6, 18),
  //     password: Random.word(6, 18),
  //     desc: Random.ctitle(4, 16),
  //     add_time: parseInt((new Date().getTime() / 1000).toFixed(0)),
  //   },
  // });
  // console.log(createResult);

  // --> createMany
  // 使用事务分别创建10个商家和100个wifi
  const transactionResult = await prisma.$transaction([
    prisma.store.createMany({
      data: new Array(5).fill(1).map(() => ({
        name: Random.ctitle(4, 16),
        address: Random.ctitle(4, 16),
        logo: Random.image("200x200", Random.hex(), Random.first()),
        tel: Random.integer(10000000000, 99999999999).toString(),
        add_time: parseInt((new Date().getTime() / 1000).toFixed(0)),
      })),
    }),
    prisma.wifi.createMany({
      data: new Array(100).fill(1).map(() => ({
        store_id: Mock.mock({
          "number|1-8": 10,
        }).number,
        ssid: Random.word(6, 18),
        password: Random.word(6, 18),
        desc: Random.ctitle(4, 16),
        add_time: parseInt((new Date().getTime() / 1000).toFixed(0)),
      })),
    }),
  ]);
  console.log(transactionResult);
}

async function query() {
  //   --> findFirst(第一条记录)
  const findFirstResult = await prisma.wifi.findFirst({
    where: {
      AND: [
        {
          ssid: {
            contains: "soj",
          },
        },
        {
          desc: {
            not: null,
          },
        },
      ],
    },
  });
  console.log(findFirstResult);

  //   --> findUnique(通过ID或唯一标识符获取记录)
  const findUniqueResult = await prisma.wifi.findUnique({
    where: {
      id: 10,
    },
  });
  console.log(findUniqueResult);

  //   --> findMany(所有记录)
  const findManyResult = await prisma.wifi.findMany({
    where: {
      id: {
        gt: 10000,
      },
    },
  });
  console.log(findManyResult);
}

async function update() {
  //   --> update
  const updateResult = await prisma.wifi.update({
    where: {
      id: 10,
    },
    data: {
      ssid: "jiajia-shop",
      password: "jiajia888",
      desc: "佳佳超市(剑南大道店)",
    },
  });
  console.log(updateResult);

  //   --> upsert
  const upsertResult = await prisma.wifi.upsert({
    where: {
      id: 20,
    },
    update: {
      password: "__qudaodian666",
      desc: "趣到店",
    },
    create: {
      store_id: 10255,
      ssid: "qudaodian",
      password: "__qudaodian666",
      desc: "趣到店",
    },
  });
  console.log(upsertResult);

  //   --> updateMany
  const updateManyResult = await prisma.wifi.updateMany({
    where: {
      ssid: "HDJS",
    },
    data: {
      desc: "易尚创客1603",
    },
  });
  console.log(updateManyResult);
}

async function remove() {
  //   --> delete
  const deleteResult = await prisma.wifi.delete({
    where: {
      id: 9,
    },
  });
  console.log(deleteResult);

  //   --> deleteMany
  const deleteManyResult = await prisma.wifi.deleteMany({
    where: {
      OR: [
        {
          ssid: "David",
        },
        {
          ssid: "update",
        },
        {
          ssid: "ssid1",
        },
      ],
    },
  });
  console.log(deleteManyResult);
}

(async function () {
  // TODO SOMETHING...
  await create();
})()
  .then(async () => {
    await prisma.$disconnect();
  })
  .catch(async (e) => {
    console.error(e);
    await prisma.$disconnect();
    process.exit(1);
  });
